package tasks.leetcode;

public class GasProblem {
    public static void main(String[] args) {
        int solution = new GasProblem().solution(new int[]{1, 2, 3, 4, 5}, new int[]{3, 4, 5, 1, 2});
        System.out.println(solution);
    }

    /**
     * gas = [1,2,3,4,5], cost = [3,4,5,1,2]
     *
     * @param gas  gas
     * @param cost cost
     */
    private int solution(int[] gas, int[] cost) {
        int currentGas = 0; // 当前拥有的汽油数量
        int totalGas = 0;// 当前总的汽油数量

        int start = 0; // 当前所处的加油站的索引

        for (int i = 0; i < gas.length; i++) {
            currentGas += gas[i] - cost[i];// 这个值一定要大于等于0，不然就开不到下一个加油站，来不及补给
            totalGas += gas[i] - cost[i]; // 这个值是到达第个加油站后，档期那还剩余油量，如果油量＜0说明，到不了终点；

            if (currentGas < 0) {
                start = i + 1;
                currentGas = 0;
            }
        }
        if (totalGas >= 0) {
            return start;
        } else {
            return -1;
        }
    }

}
